import pygame
import random

# 初始化参数
WIDTH, HEIGHT = 800, 600
CARD_SIZE = 80
ROWS = 5
COLS = 7
CARD_TYPES = 6

# 颜色定义
COLORS = [
    (255, 0, 0),  # 红
    (0, 255, 0),  # 绿
    (0, 0, 255),  # 蓝
    (255, 255, 0),  # 黄
    (255, 0, 255),  # 紫
    (0, 255, 255)  # 青
]


class Card:
    def __init__(self, card_type, row, col, layer):
        self.card_type = card_type
        self.row = row
        self.col = col
        self.layer = layer
        self.selected = False


class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("消除游戏")

        # 创建3层卡片（0为最底层）
        self.grid = [[[] for _ in range(COLS)] for _ in range(ROWS)]
        for layer in range(3):
            for row in range(ROWS):
                for col in range(COLS):
                    if random.random() < 0.7:  # 70%的概率生成卡片
                        card_type = random.randint(0, CARD_TYPES - 1)
                        self.grid[row][col].append(Card(card_type, row, col, layer))

        self.selected = []
        self.game_over = False

    def get_top_card(self, row, col):
        """获取最顶层的卡片"""
        if self.grid[row][col]:
            return self.grid[row][col][-1]
        return None

    def draw_card(self, card):
        """绘制单个卡片"""
        x = 100 + card.col * (CARD_SIZE + 10)
        y = 100 + card.row * (CARD_SIZE + 10) - card.layer * 5
        color = COLORS[card.card_type]

        if card.selected:
            pygame.draw.rect(self.screen, (255, 255, 255), (x - 2, y - 2, CARD_SIZE + 4, CARD_SIZE + 4))
        pygame.draw.rect(self.screen, color, (x, y, CARD_SIZE, CARD_SIZE))
        pygame.draw.rect(self.screen, (0, 0, 0), (x, y, CARD_SIZE, CARD_SIZE), 1)

    def check_match(self):
        """检查是否满足消除条件"""
        if len(self.selected) != 3:
            return False
        types = [card.card_type for card in self.selected]
        return types[0] == types[1] == types[2]

    def remove_cards(self):
        """移除选中的卡片"""
        for card in self.selected:
            self.grid[card.row][card.col].pop()
        self.selected = []

    def check_win(self):
        """检查是否获胜"""
        for row in range(ROWS):
            for col in range(COLS):
                if self.grid[row][col]:
                    return False
        return True

    def run(self):
        running = True
        while running:
            self.screen.fill((200, 200, 200))

            # 处理事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

                if event.type == pygame.MOUSEBUTTONDOWN and not self.game_over:
                    x, y = event.pos
                    col = (x - 100) // (CARD_SIZE + 10)
                    row = (y - 100) // (CARD_SIZE + 10)

                    if 0 <= row < ROWS and 0 <= col < COLS:
                        card = self.get_top_card(row, col)
                        if card:
                            card.selected = not card.selected
                            if card.selected:
                                self.selected.append(card)
                            else:
                                self.selected.remove(card)

                            # 检查消除
                            if len(self.selected) == 3:
                                if self.check_match():
                                    self.remove_cards()
                                    if self.check_win():
                                        self.game_over = True
                                else:
                                    # 清除选择
                                    for c in self.selected:
                                        c.selected = False
                                    self.selected = []

            # 绘制卡片
            for layer in range(3):
                for row in range(ROWS):
                    for col in range(COLS):
                        cards = self.grid[row][col]
                        if len(cards) > layer:
                            self.draw_card(cards[layer])

            # 绘制游戏结束文字
            if self.game_over:
                font = pygame.font.Font(None, 74)
                text = font.render('胜利!', True, (0, 255, 0))
                self.screen.blit(text, (WIDTH // 2 - 100, HEIGHT // 2 - 50))

            pygame.display.flip()

        pygame.quit()


if __name__ == "__main__":
    game = Game()
    game.run()